package com.yangming.springboot.deepin.playTest;

import com.yangming.springboot.deepin.Application;
import org.springframework.boot.test.context.SpringBootTest;
import org.w3c.dom.css.Counter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@SpringBootTest(classes = {Application.class})
public class AtomicTest {

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    private int i = 0;

    public static void main(String[] args) throws InterruptedException {
        final AtomicTest cas = new AtomicTest();
        List<Thread> threads = new ArrayList<Thread>(600);
        long start = System.currentTimeMillis();
        for (int j = 0; j < 100; j++){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 10000; i++){
                        cas.count();
                        cas.safeCount();
                    }
                }
            });
            threads.add(thread);
        }
        for (Thread t : threads){
            t.start();
        }
        for (Thread t : threads){
            try {
                t.join();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
        System.out.println(cas.i);
        System.out.println(cas.atomicInteger.get());
        System.out.println(System.currentTimeMillis() - start);
    }

    private void safeCount(){
        for (;;){
            int i = atomicInteger.get();
            boolean suc = atomicInteger.compareAndSet(i, ++i);
            if (suc){
                break;
            }
        }
    }

    private void count(){
        this.i++;
    }

}
